const fs = require('fs');
const path = require('path');

// 配置文件
const config = {
  targetExt: '.d.ets',          // 目标文件扩展名
  outputSuffix: '',   // 输出文件后缀
  recursive: true               // 递归子目录
};

// 核心转换函数
function transformContent(originalContent) {
  const funcRegex = /@memo\s*\n@ComponentBuilder\s*\nexport\s+declare\s+function\s+(\w+)\(([\s\S]*?)\)\s*:\s*(\w+)/g;
  
  // 保留原始内容
  let newContent = originalContent;
  
  // 查找并转换所有匹配的函数
  let match;
  while ((match = funcRegex.exec(originalContent)) !== null) {
    const [fullMatch, funcName, params, returnType] = match;
    
    // 处理参数
    const processedParams = params.split(',')
      .map(param => {
        // 保留原始参数格式
        const cleanedParam = param.trim()
          .replace(/@memo/g, '@memo()')
          .replace(/(\w+)\s*\?:\s*(.*?)\s*$/, '$1?: $2');
        return cleanedParam;
      })
      .filter(p => p);

    // 插入新参数（保留原始参数）
    processedParams.unshift(`@memo() style?: (instance: ${returnType}) => void`);

    // 生成转换后的函数
    const convertedFunction = `\n\n@memo()
function ${funcName}(
  ${processedParams.join(',\n  ')}
): void`;

    // 追加到原始内容后
    newContent += convertedFunction;
  }

  return newContent;
}

// 递归处理目录
function processDirectory(dirPath) {
  const entries = fs.readdirSync(dirPath, { withFileTypes: true });

  entries.forEach(entry => {
    const fullPath = path.join(dirPath, entry.name);
    
    if (entry.isDirectory() && config.recursive) {
      processDirectory(fullPath);
    } else if (entry.isFile() && entry.name.endsWith(config.targetExt)) {
      processFile(fullPath);
    }
  });
}

// 处理单个文件
function processFile(filePath) {
  try {
    const originalContent = fs.readFileSync(filePath, 'utf8');
    const newContent = transformContent(originalContent);
    
    // 生成新文件名
    const parsedPath = path.parse(filePath);
    const newFileName = `${parsedPath.name}${config.outputSuffix}${parsedPath.ext}`;
    const newFilePath = path.join(parsedPath.dir, newFileName);

    fs.writeFileSync(newFilePath, newContent);
    console.log(`Generated: ${path.relative(process.cwd(), newFilePath)}`);
  } catch (err) {
    console.error(`Error processing ${path.basename(filePath)}:`, err.message);
  }
}

// CLI入口
(function main() {
  const args = process.argv.slice(2);
  
  if (!args.length) {
    console.log(`
Usage:
  node process_component.js <path-to-file-or-directory>
  
Options:
  --no-recursive  Disable directory recursion
    `);
    process.exit(0);
  }

  // 解析参数
  config.recursive = !args.includes('--no-recursive');
  const targetPath = path.resolve(args.find(arg => !arg.startsWith('--')) || '.');

  console.log(`
===================================
HarmonyOS Component Processor
Target: ${targetPath}
Recursive: ${config.recursive ? 'Enabled' : 'Disabled'}
===================================
  `);

  try {
    if (fs.statSync(targetPath).isDirectory()) {
      processDirectory(targetPath);
    } else {
      processFile(targetPath);
    }
    console.log('\nProcessing completed!');
  } catch (err) {
    console.error('Fatal error:', err.message);
    process.exit(1);
  }
})();